import React, { useEffect, useRef, useState, useMemo } from 'react';
import {
    Layout,
    Table,
    Pagination,
    Button,
    Row,
    Col,
    notification,
    Spin
} from 'antd'

import {
    cityGuess,
    getResturants,
    deleteResturant
} from 'src/api/getData'


import { useNavigate } from 'react-router-dom';
import UploadModal from './UploadModal'
import './index.less'

const { Content } = Layout;

const ShopList = () => {

    const navigate = useNavigate();
    const tableRef = useRef(null);
    const [visible, setVisible] = useState(false);
    const [shopInfo, setShopInfo] = useState({});

    // 搜索条件
    const [gettingQuery, setgettingQuery] = useState({
        pageNumber: 1,
        pageSize: 10,
    })

    const [city, setCity] = useState(null)
    const [loading, setLoading] = useState(false);
    const [state, setState] = useState({});

    function handleUpdate(record) {
        setVisible(true)
        setShopInfo(record)
    }

    // 添加商品
    function handleAdd(record) {
        navigate(`/portal/addGoods?restaurant_id=${record.restaurant_id}`)
    }

    // 删除
    async function handleDelete(record) {
        try {
            setLoading(true)
            const res = await deleteResturant(record.id)
            if (res.code === 0) {
                notification.success({
                    message: res.message
                })
            }
            setLoading(false)
        } catch (error) {

        }
    }

    const columns = useMemo(() => ([
        {
            title: '店铺名称',
            dataIndex: 'name'
        },
        {
            title: '店铺地址',
            dataIndex: 'address',
        },
        {
            title: '店铺介绍',
            dataIndex: 'description',
        },
        {
            title: '操作',
            dataIndex: 'registe_time',
            render(text, record, index) {
                return <div>
                    <Button onClick={() => handleUpdate(record)}>编辑</Button>
                    <Button onClick={() => handleAdd(record)}>添加食品</Button>
                    <Button onClick={() => handleDelete(record)} type="primary" danger>删除</Button>
                </div>
            }
        },
    ]), []);

    // 获取当前城市
    useEffect(() => {
        cityGuessAsync()
    }, [])

    // 获取店铺列表
    useEffect(() => {
        if (!city) return
        const { latitude, longitude } = city;
        getResturantsAsync({
            latitude,
            longitude
        })
    }, [city])

    // 获取所在城市
    async function cityGuessAsync() {
        try {
            const res = await cityGuess();
            setCity(res.data)
        } catch (error) {

        }
    }

    // 获取
    async function getResturantsAsync(params = {}) {
        setLoading(true);
        const payload = {
            ...gettingQuery,
            ...params
        }
        setgettingQuery(payload)
        try {
            const res = await getResturants(payload);
            setState(res.data)
        } catch (err) {
            console.log('获取数据失败', err);
        }
        setLoading(false)
    }

    // 翻页
    const handlePaginationChange = (page, pageSize) => {
        getResturantsAsync({
            pageNumber: pageSize !== gettingQuery.pageSize ? 1 : page,
            pageSize,
        })
    }

    const expandable = useMemo(() => {
        return {
            expandedRowRender(record) {
                return <Row gutter={[16, 24]}>
                    <Col className="gutter-row" span={12}>
                        <span>店铺名称：</span>
                        <span>{record.name}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>店铺地址：</span>
                        <span>{record.address}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>店铺介绍：</span>
                        <span>{record.description}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>店铺 ID：</span>
                        <span>{record.id}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>联系电话：</span>
                        <span>{record.phone}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>评分：</span>
                        <span>{record.rating}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>销售量：</span>
                        <span>{record.recent_order_num}</span>
                    </Col>
                    <Col className="gutter-row" span={12}>
                        <span>分类：</span>
                        <span>{record.category}</span>
                    </Col>
                </Row>
            }
        }
    }, [])

    // 提交表单
    async function handleOk(values) {
        setShopInfo(null)
        setVisible(false)
        //刷新页面
        const { latitude, longitude } = city;
        getResturantsAsync({
            latitude,
            longitude
        })
    }

    // 取消弹框
    function handleCancel() {
        setShopInfo(null)
        setVisible(false)
    }

    return <Layout className="shop-list-container">
        <Spin spinning={loading}>
            <Content>
                <div ref={tableRef} >
                    <Table
                        rowKey="id"
                        columns={columns}
                        dataSource={state?.list || []}
                        bordered={true}
                        loading={loading}
                        pagination={false}
                        scroll={{
                            x: '100%',
                            y: 300
                        }}
                        expandable={expandable}
                    />
                </div>
                <Pagination
                    pageSizeOptions={[10, 20, 30, 50]}
                    showSizeChanger={true}
                    onShowSizeChange={handlePaginationChange}
                    onChange={handlePaginationChange}
                    showTotal={total => `共${total}条`}
                    className="ant-table-pagination ant-table-pagination-right"
                    showQuickJumper={{
                        goButton: <Button
                            style={{ marginLeft: 8 }}
                        >跳转</Button>
                    }}
                    current={gettingQuery.pageNumber}
                    pageSize={gettingQuery.pageSize}
                    total={state?.total}
                />
            </Content>
        </Spin>
        {visible && <UploadModal
            visible={visible}
            shopInfo={shopInfo}
            onOk={handleOk}
            onCancel={handleCancel}
            city={city}
        />}
    </Layout>
}

export default ShopList